<style>
    #container {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        padding: 0;
        box-sizing: border-box;
        overflow: hidden;
        background: white;
    }

    .menu {
        width: 100px;
        font-size: 14px;
        border: 1px solid #ccc;
        z-index: 1000;
        position: absolute;
        display: none;
        background: #fff;
    }

    .menu ul {
        margin: 0px;
        padding: 0px;
        text-align: center;
        list-style-type: none;
    }

    .menu ul li {
        padding: 5px 0px;
        font-size: 12px;
    }

    .menu ul li:hover {
        background: #e3e3e3;
    }

    .menu ul li a:link {
        color: #000;
        text-decoration: none;
    }

    /*  ::-webkit-scrollbar { !*滚动条整体样式*!
          width: 5px; !*高宽分别对应横竖滚动条的尺寸*!
          height: 1px;
      }

      ::-webkit-scrollbar-thumb { !*滚动条里面小方块*!
          border-radius: 10px;
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: #535353;
      }

      ::-webkit-scrollbar-track { !*滚动条里面轨道*!
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          border-radius: 10px;
          background: #EDEDED;
      }*/

    .edit {
        position: absolute;
        top: 100px;
        left: 0;
        right: 0;
        bottom: 20px;
        box-sizing: border-box;
    }

    #jsmind_container {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
</style>
<div id="container" class="fsh-rightPanel">
    <!--    <button class="layui-btn layui-btn-normal" id="btn-save">保存</button>
        <button class="layui-btn layui-btn-warm layui-btn-sm" id="btn-add">+新建目录</button>-->
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>课程设计</legend>
    </fieldset>
    <div class="edit">
        <div id="jsmind_container"></div>

    </div>
</div>

<!--右侧菜单-->
<div id="divmenu" class="menu">
    <ul>
        <li onclick="expand_all()" class="pub">展开所有</li>
        <li onclick="collapse_all()" class="pub">合并所有</li>
        <li onclick="zoomIn()" class="pub">画布放大</li>
        <li onclick="zoomOut()" class="pub">画布缩小</li>
        <li onclick="add_node();" class="add">新增子课程</li>
        <!--        <li onclick="add_upfile();" class="upload">上传文件</li>-->
        <li onclick="show_selected();" class="dispatch">指派任务</li>
        <li onclick="remove_node()" class="delete">删除子课程</li>
        <!--        <li onclick="move_node('up')" class="move">上移</li>-->
        <!--        <li onclick="move_node('down')" class="move">下移</li>-->
    </ul>
</div>

<script>
    var _jm;
    var table;
    var parentInfo = getHashParam();
    var parentId;
    var parentTitle;
    var data = [];
    layui.use(['layer', 'table', 'form'], function () {
        var layer = layui.layer;
        table = layui.table;
        parentTitle = decodeURI(parentInfo.title);
        parentId = parentInfo.id;
        data.push({"id": parentId, "isroot": true, "topic": parentTitle, 'level': 0});
        firstLoadData();

        // $(document).keydown(function (event) {
        //     if (event.keyCode == 13) {
        //         console.log('aaa');
        //     }
        // });
    });

    function firstLoadData() {
        $.ajax({
            url: context + '/api/educourse/getList?parent_id=' + parentId,
            type: "GET",
            success: function (result) {
                if (result.success) {
                    var newData = result.data;
                    for (var i = 0; i < newData.length; i++) {
                        var item = {
                            "id": newData[i].course_id,
                            "parentid": parentId,
                            "topic": newData[i].course_task,
                            'level': 1,
                            'hash': newData[i].hash
                        };
                        data.push(item);
                    }
                    console.log(data)
                    load_jsmind();
                } else {
                    layer.msg(result.msg);
                }
            }
        });

    }

    function load_jsmind() {
        var mind = {
            "meta": {
                "name": "demo",
                "author": "hizzgdev@163.com",
                "version": "0.2",
            },
            "format": "node_array",
            "data": data
        };
        var options = {
            container: 'jsmind_container',
            editable: true,
            theme: 'greensea',
            shortcut: {
                enable: false,        // 是否启用快捷键
                handles: {},         // 命名的快捷键事件处理器
                mapping: {           // 快捷键映射
                    addchild: 45,    // <Insert>
                    addbrother: 100,    // <Enter>
                    editnode: 113,   // <F2>
                    delnode: 46,    // <Delete>
                    toggle: 32,    // <Space>
                    left: 37,    // <Left>
                    up: 38,    // <Up>
                    right: 39,    // <Right>
                    down: 40,    // <Down>
                }
            }
        };
        _jm = jsMind.show(options, mind);
        $('#jsmind_container').mousedown(function (e) {
            if (e.which === 1) {  // 1 = 鼠标左键 left; 2 = 鼠标中键; 3 = 鼠标右键
                $("#divmenu").hide();
                $('#dialog-search-result').hide();
            }
        });

        $("#container").bind("contextmenu", function () {
            var div = $("#divmenu");
            if (showmenu()) div.css({
                "left": document.body.scrollLeft + event.clientX - 180,
                "top": document.body.scrollTop + event.clientY - 80
            }).show();

            return false;
        });
        //监听右侧菜单点击事件，发生点击则隐藏菜单层
        $("#divmenu").click(function (event) {
            var $this = $(event.target);
            $("#divmenu").hide();
        });
    }


    //新增节点
    function add_node() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        createNewNode({
            "parent_id": parentId,
            "course_task": '未命名',
            "major_id": parentInfo.kind,
            "difficulty_level": parentInfo.easy,
        });
    }

    //新建课程
    function createNewNode(data) {
        $.ajax({
            url: context + '/api/educourse/insertOne',
            type: 'POST',
            dataType: 'json',
            contentType: "application/json;charset-UTF-8",
            data: JSON.stringify(data),
            success: function (result) {
                if (result.success) {
                    //layer.msg("添加成功");
                    _jm.add_node(parentId, result.data.course_id, result.data.course_task, {
                        "level": 1,
                        "hash": result.data.hash
                    });
                } else {
                    layer.msg(result.msg);
                }
            },
            error: function () {
                layer.msg("添加失败");
            }
        })
    }

    //监听修改topic
    function onNodeChange(id, title) {
        var select_node = _jm.get_node(id);
        updateNode({
            course_id: id,
            course_task: title,
            hash: select_node.data.hash
        });
    }

    //编辑数据
    function updateNode(data) {
        $.ajax({
            url: context + '/api/educourse/updateOne',
            type: 'PATCH',
            dataType: 'json',
            contentType: "application/json;charset-UTF-8",
            data: JSON.stringify(data),
            success: function (result) {
                if (result.success) {
                    //layer.msg("添加成功");

                } else {
                    layer.msg(result.msg);
                }
            },
            error: function () {
                layer.msg("修改失败");
            }
        })
    }

    //上移、下移节点，direction(top,bottom)
    function move_node(direction) {
        var selected_node = _jm.get_selected_node();
        _jm.move_node(selected_node.id, "_first_");
    }

    //删除节点
    function remove_node() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        console.log(selected_node)
        var isLastNode = selected_node.children.length;
        if (isLastNode > 0) {
            layer.msg('存在子集，不能删除！');
        } else {
            _jm.remove_node(selected_node.id);
        }
    }

    //关联人员
    function show_selected() {
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if (!selected_node) {
            layer.msg('请选择一个节点！');
            return;
        }
        if (selected_node.id === 0) {
            layer.msg('根节点不支持查看！');
            return;
        }
        showDialog({
            title: '指派任务'
            , template: 'views/static/courseware/template/task.html'
            , yes: function (index, layero) {
                layui.form.on('submit(*)', function (data) {
                    $.ajax({
                        url: context + '/api/educourse/updateOne',
                        type: 'PATCH',
                        async: false,
                        dataType: 'json',
                        contentType: "application/json;charset-UTF-8",
                        data: JSON.stringify(data.field),
                        success: function (result) {
                            if (result.success) {
                                layer.msg("指派成功");
                                layer.close(index);
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                        error: function () {
                            layer.msg("指派异常");
                        }
                    })
                });
                //表单验证
                layui.form.validate();//默认form名称为add_form（可不填写）
            }
        })
    }

    //展开选择的节点
    function expand() {
        var selected_id = get_selected_nodeid();
        if (!selected_id) {
            layer.msg('please select a node first.');
            return;
        }

        _jm.expand_node(selected_id);
    }

    //合并选择的节点
    function collapse() {
        var selected_id = get_selected_nodeid();
        if (!selected_id) {
            layer.msg('please select a node first.');
            return;
        }

        _jm.collapse_node(selected_id);
    }

    //展开所有节点
    function expand_all() {
        _jm.expand_all();
        $("#jsmind_container").offset({top: ((0 - _jm)), left: 100}); //将中心点调至屏幕中心
    }

    //合并所有节点
    function collapse_all() {
        _jm.collapse_all();
        $("#jsmind_container").offset({top: ((0 - _jm)), left: 100}); //将中心点调至屏幕中心
    }

    //画布缩小
    function zoomIn() {
        if (_jm.view.zoomIn()) {
            //zoomOutButton.disabled = false;
        } else {
            //zoomInButton.disabled = true;
        }
    }

    //画布放大
    function zoomOut() {
        if (_jm.view.zoomOut()) {
            //zoomInButton.disabled = false;
        } else {
            //  zoomOutButton.disabled = true;
        }
    }

    function dragFunc(id) {
        var Drag = document.getElementById(id);
        Drag.onmousedown = function (event) {
            var ev = event || window.event;
            event.stopPropagation();
            var disX = ev.clientX - Drag.offsetLeft;
            var disY = ev.clientY - Drag.offsetTop;
            document.onmousemove = function (event) {
                var ev = event || window.event;
                Drag.style.left = ev.clientX - disX + "px";
                Drag.style.top = ev.clientY - disY + "px";
                Drag.style.cursor = "move";
            };
        };
        Drag.onmouseup = function () {
            document.onmousemove = null;
            this.style.cursor = "default";
        };
    }


    //通过JS屏蔽自带右键菜单
    document.oncontextmenu = function (e) {
        return false;
    };

    //动态化展示右键菜单
    function showmenu() {
        var selected_node = _jm.get_selected_node(); // as parent of new node

        if (!selected_node) {
            $("#divmenu ul li:not(.pub)").hide();
            $("#divmenu ul li[class='pub']").show();
        } else {
            if ((selected_node.isroot)) {
                $("#divmenu ul li:not(.add)").hide();
                $("#divmenu ul li[class='add']").show();
            } else if (selected_node.data.level === 1) {
                // $(".pub,.update,.view,.history,.delete").hide();
                // $(".sel,.upload,.add,.move").show();
                $(".pub,.add").hide();
                $(".delete,.dispatch").show();
            }
        }
        return true;
    }


    //鼠标滚轮缩放
    // $('#jsmind_container').onmousewheel = document.onmousewheel = function (e) {
    //     e = e || window.event;
    //     if (e.wheelDelta) {  //判断浏览器IE，谷歌滑轮事件
    //         if (e.wheelDelta > 0) { //当滑轮向上滚动时
    //             _jm.view.zoomIn()
    //         }
    //         if (e.wheelDelta < 0) { //当滑轮向下滚动时
    //             _jm.view.zoomOut();
    //         }
    //     } else if (e.detail) {  //Firefox滑轮事件
    //         if (e.detail > 0) { //当滑轮向下滚动时
    //             _jm.view.zoomOut();
    //         }
    //         if (e.detail < 0) { //当滑轮向上滚动时
    //             _jm.view.zoomIn()
    //         }
    //     }
    // };

</script>
